package com.aaa.aop;

import com.aaa.entity.Login_log;
import com.aaa.result.Result;
import com.aaa.service.LogService;
import com.aaa.vo.LoginVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

@Component
@Aspect
@Slf4j
public class AopLog {


    @Autowired
    private LogService service;

    private String addr=null;
    private String uri=null;
    private Object[] args = null;

    private long start = 0;

    @Pointcut("execution(* com.aaa.controller.*.*(..))")
    public  void  haha(){}

    @Before("haha()")
    public  void  before(JoinPoint point){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();

        addr = request.getRemoteAddr();
        uri = request.getRequestURI();
        args = point.getArgs();

        start = System.currentTimeMillis();
        log.info("===================请求的地址是:================="+addr);
        log.info("===================请求的路径是:================="+uri);
        log.info("===================请求的参数是:================="+ Arrays.toString(args));

    }



    @AfterReturning(returning = "data", pointcut = "execution(* com.aaa.controller.AuthController.login(..))")
    public  void  after(JoinPoint joinPoint, Result data) throws Exception {

        //调用controller之后状态码
        Integer code = data.getCode();
        //获取登陆账号，密码
        LoginVO login = (LoginVO) args[0];
        String username = login.getUsername();
        String password = login.getPassword();
        //当前时间
        Date date = new Date();
        //调用添加日志的方法
        Login_log log = new Login_log(0, username, date, code, addr, password);
        Result result = service.InsertLog(log);
        System.out.println("AOP==================="+result.getMessage());
        long end = System.currentTimeMillis();
        AopLog.log.info("=================耗时================="+ (end-start)+"(ms)");
        AopLog.log.info("=================结束了=================");
    }


}
